package com.tanhua.dubbo.api.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.PageUtil;
import cn.hutool.core.util.StrUtil;
import com.tanhua.dubbo.api.QuanZiApi;
import com.tanhua.dubbo.api.VideoApi;
import com.tanhua.dubbo.api.service.IdService;
import com.tanhua.dubbo.api.service.TimeLineService;
import com.tanhua.dubbo.enums.CommentType;
import com.tanhua.dubbo.enums.IdType;
import com.tanhua.dubbo.pojo.*;
import com.tanhua.dubbo.vo.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.ArrayList;
import java.util.List;

@DubboService(version = "1.0.0")
@Slf4j
public class QuanZiApiImpl implements QuanZiApi {

    //评论数据存储在Redis中key的前缀
    private static final String COMMENT_REDIS_KEY_PREFIX = "QUANZI_COMMENT_";

    //用户是否点赞的前缀
    private static final String COMMENT_USER_LIKE_REDIS_KEY_PREFIX = "USER_LIKE_";

    //用户是否喜欢的前缀
    private static final String COMMENT_USER_LOVE_REDIS_KEY_PREFIX = "USER_LOVE_";

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdService idService;

    @Autowired
    private TimeLineService timeLineService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @DubboReference(version = "1.0.0")
    private VideoApi videoApi;
    /**
     * 查询好友动态(刷朋友圈)
     *
     * @param userId   用户id
     * @param page     当前页数
     * @param pageSize 每一页查询的数据条数
     * @return
     */
    @Override
    public PageInfo<Publish> queryPublishList(Long userId, Integer page, Integer pageSize) {

        PageRequest pageRequest = PageRequest.of(page - 1, pageSize,
                Sort.by(Sort.Order.desc("date")));
        Query query = new Query().with(pageRequest);

        //查询自己的时间线表即可
        List<TimeLine> timeLineList =
                this.mongoTemplate.find(query, TimeLine.class, "quanzi_time_line_" + userId);

        List<Object> publishIdList = CollUtil.getFieldValues(timeLineList, "publishId");

        //查询发布对象
        Query publishQuery = Query.query(Criteria.where("id").in(publishIdList))
                .with(Sort.by(Sort.Order.desc("created")));
        List<Publish> publishList = this.mongoTemplate.find(publishQuery, Publish.class);

        PageInfo<Publish> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);
        pageInfo.setRecords(publishList);
        return pageInfo;
    }

    @Override
    public String savePublish(Publish publish) {
        //校验数据是否完整
        if (!ObjectUtil.isAllNotEmpty(publish.getUserId(),
                publish.getText(), publish.getMedias())) {
            return null;
        }

        publish.setId(ObjectId.get());
        publish.setPid(this.idService.createId(IdType.PUBLISH));//自增长的Long类型id
        publish.setCreated(System.currentTimeMillis());
        publish.setSeeType(1);

        //保存到发布表
        this.mongoTemplate.save(publish);

        //写入到自己的相册表
        Album album = new Album();
        album.setId(ObjectId.get());
        album.setPublishId(publish.getId());
        album.setCreated(System.currentTimeMillis());
        this.mongoTemplate.save(album, "quanzi_album_" + publish.getUserId());

        //写入到好友的时间线表（异步的写入）
        //异步的实现底层原理：在这里再开一个线程去执行即可
        this.timeLineService.saveTimeLine(publish.getUserId(), publish.getId());

        return publish.getId().toHexString();
    }

    /**
     * 查询推荐动态  数据源在redis中
     *
     * @param userId   用户id
     * @param page     当前页数
     * @param pageSize 每一页查询的数据条数
     * @return
     */
    @Override
    public PageInfo<Publish> queryRecommendPublishList(Long userId, Integer page,
                                                       Integer pageSize) {
        PageInfo<Publish> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);

        //首先从redis中查询数据
        String redisKey = "QUANZI_PUBLISH_RECOMMEND_" + userId;
        String redisData = this.redisTemplate.opsForValue().get(redisKey);
        if (StrUtil.isEmpty(redisData)) {
            return pageInfo;
        }

        //数据源
        List<String> pidList = StrUtil.split(redisData, ',');

        //手动分页
        int[] startEnd = PageUtil.transToStartEnd(page - 1, pageSize);
        int start = startEnd[0]; //开始下标
        int end = Math.min(pidList.size(), startEnd[1]); // 结束下标

        //真正返回的数据集合
        List<Long> pids = new ArrayList<>();
        for (int i = start; i < end; i++) {
            pids.add(Convert.toLong(pidList.get(i)));
        }

        //查询发布对象数据
        Query query = Query.query(Criteria.where("pid").in(pids));
        List<Publish> publishList = this.mongoTemplate.find(query, Publish.class);

        //按照推荐的结果顺序进行排序
        pageInfo.setRecords(new ArrayList<>());
        for (Long pid : pids) {
            for (Publish publish : publishList) {
                if (ObjectUtil.equal(publish.getPid(), pid)) {
                    pageInfo.getRecords().add(publish);
                    break;
                }
            }
        }

        return pageInfo;
    }

    /**
     * 根据id查询动态
     *
     * @param id 动态id
     * @return
     */
    @Override
    public Publish queryPublishById(String id) {
        return this.mongoTemplate.findById(new ObjectId(id), Publish.class);
    }

    /**
     * 点赞
     *
     * @param userId
     * @param publishId
     * @return
     */
    @Override
    public Boolean likeComment(Long userId, String publishId) {
        // 判断该用户是否对该动态已经点赞
        if (this.queryUserIsLike(userId, publishId)) {
            return false;
        }

        //将数据保存到MongoDB
        Comment comment = new Comment();
        comment.setId(ObjectId.get());
        comment.setCommentType(CommentType.LIKE.getType());
        comment.setCreated(System.currentTimeMillis());
        comment.setPublishId(new ObjectId(publishId));
        comment.setIsParent(false);

        //查询动态
        Publish publish = this.queryPublishById(publishId);
        comment.setUserId(userId);
        if (null != publish) {
            comment.setPublishUserId(publish.getUserId());
        } else {
            // 对于评论点赞
            Comment commentObj = this.mongoTemplate.findById(new ObjectId(publishId), Comment.class);
            if (null != commentObj) {
                comment.setPublishUserId(commentObj.getUserId());
            }
        }
        this.mongoTemplate.save(comment);

        //将点赞数以及用户是否点赞记录到redis中
        String redisKey = this.getCommentRedisKey(publishId);
        String hashKey = CommentType.LIKE.name();
        //点赞数
        this.redisTemplate.opsForHash().increment(redisKey, hashKey, 1);

        //标识该用户已经点赞
        this.redisTemplate.opsForHash().put(redisKey, this.getCommentUserLikeRedisKey(userId), "1");

        return true;
    }

    /**
     * 根据动态id返回redis的key
     *
     * @param publishId
     * @return
     */
    private String getCommentRedisKey(String publishId) {
        return COMMENT_REDIS_KEY_PREFIX + publishId;
    }

    /**
     * 根据用户id返回hashkey
     *
     * @param userId
     * @return
     */
    private String getCommentUserLikeRedisKey(Long userId) {
        return COMMENT_USER_LIKE_REDIS_KEY_PREFIX + userId;
    }

    /**
     * 取消点赞
     *
     * @param userId
     * @param publishId
     * @return
     */
    @Override
    public Boolean disLikeComment(Long userId, String publishId) {
        //判断该用户是否有点赞
        if (!this.queryUserIsLike(userId, publishId)) {
            return false;
        }

        //删除MongoDB中的点赞记录
        Query query = Query.query(Criteria.where("userId").is(userId)
                .and("publishId").is(new ObjectId(publishId))
                .and("commentType").is(CommentType.LIKE.getType()));
        this.mongoTemplate.remove(query, Comment.class);

        //修改redis中的数据
        String redisKey = this.getCommentRedisKey(publishId);
        String hashKey = CommentType.LIKE.name();
        //点赞数
        this.redisTemplate.opsForHash().increment(redisKey, hashKey, -1);

        //删除已点赞的标识
        this.redisTemplate.opsForHash().delete(redisKey, this.getCommentUserLikeRedisKey(userId));

        return true;
    }

    /**
     * 查询点赞数
     *
     * @param publishId
     * @return
     */
    @Override
    public Long queryLikeCount(String publishId) {
        String redisKey = this.getCommentRedisKey(publishId);
        String hashKey = CommentType.LIKE.name();
        return Convert.toLong(this.redisTemplate.opsForHash().get(redisKey, hashKey), 0L);
    }

    /**
     * 查询用户是否点赞该动态
     *
     * @param userId
     * @param publishId
     * @return
     */
    @Override
    public Boolean queryUserIsLike(Long userId, String publishId) {
        String redisKey = this.getCommentRedisKey(publishId);
        String hashKey = this.getCommentUserLikeRedisKey(userId);
        return this.redisTemplate.opsForHash().hasKey(redisKey, hashKey);
    }

    /**
     * 根据用户id返回hashkey  喜欢
     *
     * @param userId
     * @return
     */
    private String getCommentUserLoveRedisKey(Long userId) {
        return COMMENT_USER_LOVE_REDIS_KEY_PREFIX + userId;
    }

    /**
     * 喜欢
     *
     * @param userId
     * @param publishId
     * @return
     */
    @Override
    public Boolean loveComment(Long userId, String publishId) {
        //判断该用户是否喜欢
        if (this.queryUserIsLove(userId, publishId)) {
            return false;
        }
        //将数据保存到MongoDB
        Comment comment = new Comment();
        comment.setId(ObjectId.get());
        comment.setCommentType(CommentType.LOVE.getType());
        comment.setCreated(System.currentTimeMillis());
        comment.setParentId(new ObjectId(publishId));
        comment.setIsParent(false);
        //查询动态
        Publish publish = this.queryPublishById(publishId);
        comment.setUserId(userId);
        comment.setPublishUserId(publish.getUserId());
        this.mongoTemplate.save(comment);
        //将喜欢以及用户是否喜欢记录到redis
        String redisKey = this.getCommentRedisKey(publishId);
        String hashKey = CommentType.LOVE.name();
        //喜欢数
        this.redisTemplate.opsForHash().increment(redisKey, hashKey, 1);
        //标记该用户已经喜欢
        this.redisTemplate.opsForHash().put(redisKey, this.getCommentUserLoveRedisKey(userId), "1");
        return true;
    }

    /**
     * 取消喜欢
     *
     * @param userId
     * @param publishId
     * @return
     */
    @Override
    public Boolean disLoveComment(Long userId, String publishId) {
        //判断该用户是否喜欢
        if (!this.queryUserIsLove(userId, publishId)) {
            return false;
        }
        //删除喜欢记录
        Query query = Query.query(Criteria.where("userId").is(userId)
                .and("publishId").is(publishId)
                .and("commentType").is(CommentType.LOVE.getType()));
        this.mongoTemplate.remove(query, Comment.class);
        //修改redis中的数据
        String redisKey = this.getCommentRedisKey(publishId);
        String hashKey = CommentType.LOVE.name();
        //喜欢数
        this.redisTemplate.opsForHash().increment(redisKey, hashKey, -1);
        //删除以喜欢的标识
        this.redisTemplate.opsForHash().delete(redisKey, this.getCommentUserLoveRedisKey(userId));
        return true;
    }

    /**
     * 查询喜欢数
     *
     * @param publishId
     * @return
     */
    @Override
    public Long queryLoveCount(String publishId) {
        String redisKey = this.getCommentRedisKey(publishId);
        String hashKey = CommentType.LOVE.name();
        return Convert.toLong(this.redisTemplate.opsForHash().get(redisKey, hashKey), 0L);
    }

    /**
     * 查询用户是否喜欢该动态
     *
     * @param userId
     * @param publishId
     * @return
     */
    @Override
    public Boolean queryUserIsLove(Long userId, String publishId) {
        String redisKey = this.getCommentRedisKey(publishId);
        String hashKey = this.getCommentUserLoveRedisKey(userId);
        return this.redisTemplate.opsForHash().hasKey(redisKey, hashKey);
    }

    /**
     * 查询评论
     *
     * @return
     */
    @Override
    public PageInfo<Comment> queryCommentList(String publishId, Integer page, Integer pageSize) {
        PageRequest pageRequest = PageRequest.of(page - 1, pageSize, Sort.by(Sort.Order.desc("created")));
        Query query = new Query(Criteria.where("publishId").is(new ObjectId(publishId))
                .and("commentType").is(CommentType.COMMENT.getType())).with(pageRequest);
        //查询MongoDB中的评论列表
        List<Comment> commentList = this.mongoTemplate.find(query, Comment.class);
        PageInfo<Comment> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);
        pageInfo.setRecords(commentList);
        return pageInfo;
    }

    /**
     * 发表评论
     *
     * @param userId
     * @param publishId
     * @param content
     * @return
     */
    @Override
    public Boolean saveComment(Long userId, String publishId, String content) {
        return this.saveComment(userId, publishId, CommentType.COMMENT, content);
    }

    private Boolean saveComment(Long userId, String publishId, CommentType commentType) {
        return this.saveComment(userId, publishId, commentType, null);
    }

    private Boolean saveComment(Long userId, String publishId, CommentType commentType, String content) {
        if (StrUtil.isEmpty(content)) {
            return false;
        }
        try {
            Comment comment = new Comment();
            comment.setId(ObjectId.get());
            comment.setUserId(userId);
            comment.setPublishId(new ObjectId(publishId));
            comment.setCommentType(commentType.getType());
            comment.setCreated(System.currentTimeMillis());
            //根据发布id查询动态
            Publish publish = this.queryPublishById(publishId);
            if (null != publish) {
                comment.setPublishUserId(publish.getUserId());
            } else {
                //对于评论点赞
                Comment commentObj = this.mongoTemplate.findById(new ObjectId(publishId), Comment.class);
                if (null != commentObj) {
                    comment.setPublishUserId(commentObj.getUserId());
                } else {
                    //查询小视频
                    Video video = this.videoApi.queryVideoById(publishId);
//                    Video video = this.mongoTemplate.findById(new ObjectId(publishId), Video.class);
                    if (video != null) {
                        comment.setPublishUserId(video.getUserId());
                    } else {
                        return false;
                    }
                }
            }

            comment.setContent(content);
            //评论数据保存到MongoDB中
            this.mongoTemplate.save(comment);

            String redisKey = this.getCommentRedisKey(publishId);
            String hashKey = CommentType.COMMENT.name();

            this.redisTemplate.opsForHash().increment(redisKey, hashKey, 1);
            return true;
        } catch (Exception e) {
            log.error("saveComment error! ", e);
        }
        return false;
    }

    /**
     * 评论数
     *
     * @param publishId
     * @return
     */
    @Override
    public Integer queryCommentCount(String publishId) {
        Query query = Query.query(Criteria.where("publishId").is(new ObjectId(publishId))
                .and("commentType").is(CommentType.COMMENT.getType()));
        List<Comment> comments = this.mongoTemplate.find(query, Comment.class);
        return comments.size();
    }

    /**
     * 查询相册表
     *
     * @param userId
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public PageInfo<Publish> queryAlbumList(Long userId, Integer page, Integer pageSize) {
        PageInfo<Publish> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);
        //查询我的相册表 ->发布id列表
        PageRequest pageRequest = PageRequest.of(page - 1, pageSize, Sort.by(Sort.Order.desc("created")));
        Query query = new Query().with(pageRequest);
        List<Album> albumList = this.mongoTemplate.find(query, Album.class, "quanzi_album_" + userId);
        //根据发布id查询发布对象
        List<Object> publishIdList = CollUtil.getFieldValues(albumList, "publishId");
        Query publishQuery = Query.query(Criteria.where("id").in(publishIdList))
                .with(Sort.by(Sort.Order.desc("created")));
        List<Publish> publishList = this.mongoTemplate.find(publishQuery, Publish.class);
        pageInfo.setRecords(publishList);
        return pageInfo;
    }

    /**
     * 查询对我的点赞消息列表
     *
     * @return
     */
    @Override
    public PageInfo<Comment> queryLikeCommentListByUser(Long userId, Integer page, Integer pageSize) {
        return this.queryCommentListByUser(userId, CommentType.LIKE, page, pageSize);
    }

    /**
     * 查询对我的喜欢消息列表
     *
     * @return
     */
    @Override
    public PageInfo<Comment> queryLoveCommentListByUser(Long userId, Integer page, Integer pageSize) {
        return this.queryCommentListByUser(userId, CommentType.LOVE, page, pageSize);
    }

    /**
     * 查询对我的评论消息列表
     *
     * @return
     */
    @Override
    public PageInfo<Comment> queryCommentListByUser(Long userId, Integer page, Integer pageSize) {
        return this.queryCommentListByUser(userId, CommentType.COMMENT, page, pageSize);
    }

    private PageInfo<Comment> queryCommentListByUser(Long userId, CommentType commentType, Integer page, Integer pageSize) {
        PageRequest pageRequest = PageRequest.of(page - 1, pageSize,
                Sort.by(Sort.Order.desc("created")));

        Query query = new Query(Criteria
                .where("publishUserId").is(userId)
                .and("commentType").is(commentType.getType())).with(pageRequest);

        List<Comment> commentList = this.mongoTemplate.find(query, Comment.class);

        PageInfo<Comment> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);
        pageInfo.setRecords(commentList);
        return pageInfo;
    }
}
